package com.clock.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.clock.common.constant.HttpStatus;
import com.clock.common.domain.R;
import com.clock.common.exception.BizException;
import com.clock.common.utils.LocalDateTimeUtil;
import com.clock.common.utils.bean.BeanUtils;
import com.clock.domain.dto.PostRelatedTagDTO;
import com.clock.domain.entity.Comment;
import com.clock.domain.entity.DiscussPost;
import com.clock.common.utils.SensitiveWordUtil;
import com.clock.domain.dto.InsertDiscussPostDTO;
import com.clock.domain.entity.Tag;
import com.clock.domain.entity.User;
import com.clock.domain.vo.DiscussPostDetailVO;
import com.clock.mapper.*;
import com.clock.service.CommentService;
import com.clock.service.DiscussPostService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author flm
 *
 */
@Transactional
@Service
public class DiscussPostServiceImpl implements DiscussPostService {

    @Resource
    DiscussPostMapper discussPostMapper;

    @Resource
    CommentMapper commentMapper;

    @Resource
    CommentService commentService;

    @Resource
    UserMapper userMapper;

    @Resource
    PostRelatedTagMapper postRelatedTagMapper;

    @Resource
    TagMapper tagMapper;

    @Resource
    TagModuleMapper tagModuleMapper;

    @Resource
    FollowMapper followMapper;

    /**
     * 分页查询正常帖子
     * @author flm
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R getNormalDiscussPostByLimit(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<DiscussPost> list = discussPostMapper.queryNormalByLimit();

        for (DiscussPost discussPost : list) {
            User user = userMapper.queryById(discussPost.getUserId().intValue());
            discussPost.setUserName(user.getUserName());
        }

        if (list == null || list.size() == 0) {
            return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
        }
        PageInfo pageInfo = new PageInfo(list);

        return R.ok(pageInfo);
    }

    /**
     * 查询所有帖子
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R getAllDiscussPostByLimit(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<DiscussPost> list = discussPostMapper.queryAllByLimit();

        for (DiscussPost discussPost : list) {
            User user = userMapper.queryById(discussPost.getUserId().intValue());
            discussPost.setUserName(user.getUserName());
        }

        if (list == null || list.size() == 0) {
            return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
        }
        PageInfo pageInfo = new PageInfo(list);

        return R.ok(pageInfo);
    }


    /**
     * 查询帖子详情和对应的评论
     * @param id
     * @param pageNum
     * @return
     */
    @Override
    public R getDiscussPostAndCommentsById(Long id,Integer pageNum) {

        if (id == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数异常");
        }

        List<Map<String, Object>> list = new ArrayList<>();

        DiscussPostDetailVO detailVO;

        try {
            DiscussPost discussPost = discussPostMapper.queryDiscussPostById(id);
            detailVO = BeanUtils.copyBean(discussPost, DiscussPostDetailVO.class);
            detailVO.setUserId(discussPost.getUserId().intValue());
            Integer[] tagIds = postRelatedTagMapper.queryTags(discussPost.getPostId(), discussPost.getUserId());
            List<Tag> tagList = tagMapper.queryTagsById(tagIds);
            List<String> tags = new LinkedList<>();
            List<String> modules = null;
            Set<Integer> moduleIds = new HashSet<>();
            for (Tag tag : tagList) {
                tags.add(tag.getTagContent());
                moduleIds.add(tag.getTagModuleId());
            }
            if(!moduleIds.isEmpty()){
                modules = tagModuleMapper.queryModulesById(moduleIds);
            }
            

            //将标签和模块赋给Vo
            detailVO.setTags(tags);
            detailVO.setModules(modules);
            detailVO.setUserName(userMapper.queryById(discussPost.getUserId().intValue()).getUserName());

            //获取对帖子的评论
            PageInfo<Comment> comments = getCommentsToPost(discussPost.getPostId(), pageNum, 5);

            detailVO.setComments(comments);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(HttpStatus.ERROR, "内部异常");
        }

        if (detailVO == null) {
            throw new BizException(HttpStatus.ERROR, "查询异常");
        }
        return R.ok(detailVO);
    }

    @Override
    public R getDiscussPostsBySearch(String keywords, Integer pageNum, Integer pageSize) {

        if (keywords == null || keywords == "") {
            throw new BizException(HttpStatus.BAD_REQUEST, "关键字错误,请重新搜索");
        }

        if (pageNum == null || pageSize == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数错误");
        }
        String realKeys = "%" + keywords + "%";
        PageHelper.startPage(pageNum, pageSize);
        List<DiscussPost> list = discussPostMapper.queryAllBySearch(realKeys);

        if (list == null || list.size() == 0) {
            return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
        }

        for (DiscussPost discussPost : list) {
            User user = userMapper.queryById(discussPost.getUserId().intValue());
            discussPost.setUserName(user.getUserName());
        }

        PageInfo pageInfo = new PageInfo(list);
        return R.ok(pageInfo);

    }


    @Override
    public R deleteDiscussPostById(Long postId) {
        if (postId == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数异常");
        }

        try {
            // 删除帖子
            discussPostMapper.deleteDiscussPostById(postId);

            // 删除帖子中的评论
            commentMapper.deleteCommentByEntityId(postId);


        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(HttpStatus.ERROR, "删除失败");
        }

        return R.ok("删除成功");
    }

    /**
     * 逻辑删除帖子
     * @param postId
     * @param status
     * @return
     */
    @Override
    public R deleteLogicDiscussPostById(Long postId, Integer status) {

        DiscussPost discussPost = discussPostMapper.queryDiscussPostById(postId);
        if (discussPost == null) {
            return R.fail("无此记录");
        }

        Integer success = discussPostMapper.updatePostStatus(postId, status);
        if (success == 1) {
            return R.ok("删除成功");
        }else {
            return  R.ok("删除失败");
        }

    }

    /**
     * 查询个人帖子
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R queryPostOfOwn(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<DiscussPost> list = discussPostMapper.queryPostsOfOwn(userId);
        if(!list.isEmpty()){
            for (DiscussPost discussPost : list) {
                String userName = userMapper.queryById(discussPost.getUserId().intValue()).getUserName();
                discussPost.setUserName(userName);
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        if (list == null || list.size() == 0) {
            return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
        }

        return R.ok(pageInfo);
    }

    /**
     * 查询用户可能感兴趣的帖子
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R queryUserMaybeLike(Long userId, Integer pageNum, Integer pageSize) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<DiscussPost> list = discussPostMapper.queryUserMayBeLike(userId);

            if (list == null || list.size() == 0) {
                return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
            }
            for (DiscussPost discussPost : list) {
                String userName = userMapper.queryById(discussPost.getUserId().intValue()).getUserName();
                discussPost.setUserName(userName);
            }
            PageInfo pageInfo = new PageInfo(list);
            return R.ok(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return R.ok(HttpStatus.NO_CONTENT, "暂无数据");
        }

    }

    /**
     * 查询用户关注人的部分帖子
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R queryFollowersOfPartPost(Long userId, Integer pageNum, Integer pageSize) {

        Set<Long> followerIds = followMapper.selectFollowsByUserId(userId);

        if (followerIds == null || followerIds.isEmpty()) {
            return R.ok(HttpStatus.NO_CONTENT, "暂时无好友文章推送");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<DiscussPost> list = discussPostMapper.queryFollowOfPosts(followerIds);

        if (list == null || list.size() == 0) {
            return R.ok(HttpStatus.NO_CONTENT, "近期暂无好友文章");
        }

        for (DiscussPost discussPost : list) {
            String userName = userMapper.queryById(discussPost.getUserId().intValue()).getUserName();
            discussPost.setUserName(userName);
        }
        PageInfo pageInfo = new PageInfo(list);

        return R.ok(pageInfo);
    }


    /**
     * 获取对帖子的评论
     *
     * @return
     */
    private PageInfo<Comment> getCommentsToPost(Long id, Integer pageNum, Integer pageSize) {

        if (id == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数异常");
        }

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Comment> commentsByLimit = commentService.getCommentsByLimit(id, pageNum, pageSize);
        System.out.println("总数" + commentsByLimit.getTotal());
        if (commentsByLimit == null) {
            R.ok(HttpStatus.NO_CONTENT, "暂无评论");
        }
        return commentsByLimit;
    }

    /**
     * 获取回复帖子
     *
     * @return
     */
    private List<Comment> getCommentsToReply(Long id, Integer pageNum) {

        if (id == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数异常");
        }

        //查询对帖子的评论
        PageInfo<Comment> commentPageInfo = commentService.getReplyCommentsByLimit(id, pageNum);
        return commentPageInfo.getList();
    }

    /**
     * 发布新帖子
     * @author flm
     * @param newDiscussPostDto 帖子详情
     * @return
     */
    @Override
    public R insertNewDiscussPostByUserId(InsertDiscussPostDTO newDiscussPostDto) throws Exception {

        if (newDiscussPostDto == null) {
            throw new BizException(HttpStatus.BAD_REQUEST, "参数异常");
        }
        // 1.过滤标题与内容是否有敏感词,并替换敏感词
        try {
            String tranTitle = SensitiveWordUtil.sensitiveHelper(newDiscussPostDto.getTitle());
            String tranContent = SensitiveWordUtil.sensitiveHelper(newDiscussPostDto.getContent());
            newDiscussPostDto.setTitle(tranTitle);
            newDiscussPostDto.setContent(tranContent);
        } catch (IOException e) {
            throw new BizException(HttpStatus.ERROR, "过滤敏感词出错");
        }

        //帖子创建时间
        LocalDateTime insertTime = LocalDateTimeUtil.getLocalDateTime();
        Date nowTime = LocalDateTimeUtil.LocalDateTimeToDate(insertTime);

        newDiscussPostDto.setCreateTime(nowTime);

        PostRelatedTagDTO postRelatedTagDTO = new PostRelatedTagDTO();



        // 2.写入数据库
        try {
            discussPostMapper.insertDiscussPost(newDiscussPostDto);
            postRelatedTagDTO.setPostId(discussPostMapper.queryPostId(nowTime, newDiscussPostDto.getUserId()))
                    .setTagIds(newDiscussPostDto.getTags())
                    .setUserId(newDiscussPostDto.getUserId());
            postRelatedTagMapper.insertRelevances(postRelatedTagDTO);
            return R.ok("发布成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.fail("发布失败");
        }


//        try {
//              // 2.写入数据库
//                discussPostMapper.insertDiscussPost(newDiscussPostDto);
//
//              // 3.重新从数据库捞出确认存入缓存
//                discussPost = discussPostMapper.queryDiscussPostByUserIdAnCreateTime(newDiscussPostDto.getUserId(), newDiscussPostDto.getCreateTime());
//
//        } catch (Exception e) {
//            throw new BizException(HttpStatus.ERROR, "发布失败");
//        }
//
//        // 4.写入缓存
//        if (discussPost == null) {
//
//            throw new BizException(HttpStatus.ERROR, "发布失败");
//        }
//
//        String CACHE_KEY = DiscussPostCacheKey.DISCUSS_POST_PRE_CACHE_KEY + discussPost.getPostId();
//
//        try {
//            //对象转map
//            Map<String, Object> map = ObjectTransformUtil.getObjectToMap(discussPost);
//
//            //批量写入属性
//            redisUtil.hmset(CACHE_KEY, map);
//        } catch (Exception e) {
//            throw new BizException(HttpStatus.ERROR, "服务器跑路了");
//        }
//        return R.ok(redisUtil.hmget(CACHE_KEY));


    }



}
